#!/bin/bash
#====================================================
#                 参数检查
#====================================================
FILE_COUNT=$#
if((FILE_COUNT!=3)); then
    echo ">>> 错误：未传递文件参数！"
    echo "  用法：keepalive.sh [参数一：master｜backup] [参数二：vip如：192.168.xxx.xxx][参数三：网卡名]"
    exit;
fi
#====================================================
#                 安装keepalive
#====================================================
if [ "$(command -v keepalived)" ]; then
    echo "--------当前系统已经安装了keepalive---------"
else
    echo "--------开始安装keepalive---------"
    yum install -y keepalived # 安装
    systemctl enable keepalived # 开始启动
    systemctl start keepalived # 启动
    ps -ef | grep keepalived # 查看进程
fi
#====================================================
#                 配置脚本准备
#====================================================
echo "--------开始配置keepalive检测脚本---------"
# 参数一：主备机状态大小写转换
case "$1" in
    "master")
        STATE=$(echo $1 | tr 'a-z' 'A-Z') 
    ;;
    "backup")
        STATE=$(echo $1 | tr 'a-z' 'A-Z') 
    ;;
    *)
    echo "错误：keepalive.sh [参数一：master｜backup] [参数二：vip如：192.168.xxx.xxx][参数三：网卡名]"
    exit
    ;;
esac
VIP=$2
NET_NAME=$3
SCRIPT_HOME="/etc/keepalived"
SCRIPT_CONF="$SCRIPT_HOME/keepalived.conf"
SCRIPT_CHECK="$SCRIPT_HOME/check_alive.sh"
SCRIPT_NOTIFY="$SCRIPT_HOME/notify.sh"

cp check_alive.sh $SCRIPT_CHECK
cp notify.sh $SCRIPT_NOTIFY

# 当前脚本目录
echo "脚本变量：主备状态【$STATE】vip【$VIP】网卡名【$NET_NAME】"
echo "脚本变量：存活检查脚本【$SCRIPT_CHECK】"
echo "脚本变量：状态切换脚本【$SCRIPT_NOTIFY】"

#====================================================
#                 系统命令、开机服务
#====================================================

sudo cat >/etc/keepalived/keepalived.conf<<EOF
vrrp_script check_alive {
    script "$SCRIPT_CHECK"
    interval 1    #每隔1秒执行上述的脚本，检查服务状态
    weight -3     #宕机一次将自身权重减3
    fall 2
    rise 2
    timeout 6
}

vrrp_instance VI_1 {
    state $STATE
    interface $NET_NAME
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        $VIP/24
    }
        # 新增检测Nginx脚本 自定义脚本名check_nginx_alive
    track_script {
        check_alive
    }

    # keepalived 三个接口，当状态改变时执行用户自定义脚本
    notify_master "$SCRIPT_NOTIFY master"
    notify_backup "$SCRIPT_NOTIFY backup"
    notify_fault "$SCRIPT_NOTIFY fault"
}
EOF
# 参数自定义脚本不执行
chcon -t keepalived_unconfined_script_exec_t  /etc/keepalived/notify.sh
systemctl restart keepalived # 重新启动
# ./keepalive.sh master 192.168.56.200 enp0s8
# ./keepalive.sh backup 192.168.56.200 enp0s8
# scp -r monitor_env_install/ root@192.168.56.102:/root
# tail -f /var/log/messages




